﻿using System.Collections.Generic;
using System.Windows.Forms.Integration;
using System.Windows.Interactivity;
using System.Windows.Forms;
using BaseTypesLib.Model;
using System.Linq;
using BBInterfaceNET.PropertiesWindow.ViewModels;
using System.Windows;

namespace BBInterfaceNET.PropertiesWindow.Behaviors
{
    public class WFHostBehavior:Behavior<WindowsFormsHost>
    {

        protected override void OnAttached()
        {
            base.OnAttached();            
            AssociatedObject.DataContextChanged += AssociatedObject_DataContextChanged;
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
            
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            PropertyGrid pg = AssociatedObject.Child as PropertyGrid;
            if (pg != null)
            {
                pg.PropertyValueChanged += pg_PropertyValueChanged;
            }
        }

        void AssociatedObject_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            //link the data context to the propertiyGrid
            PropertyGrid pg = AssociatedObject.Child as PropertyGrid;
            if (pg != null)
            {
                pg.SelectedObject = AssociatedObject.DataContext;
            }
        }

        void pg_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            var vm = ((FrameworkElement)AssociatedObject.Parent).DataContext as PropertiesViewModel;
            if (vm != null)
            {
                vm.RaiseFieldPropertyChanged(e.ChangedItem.Value, e.OldValue);
            }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.DataContextChanged -= AssociatedObject_DataContextChanged;
            var field = AssociatedObject.DataContext as Field;
            if (field != null)
            {
                PropertyGrid pg = AssociatedObject.Child as PropertyGrid;

                if (pg != null)
                {
                    pg.PropertyValueChanged -= pg_PropertyValueChanged;
                }
            }
        }
    }
}
